package com.alex.webnote.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.alex.common.ILogger;
import com.alex.common.security.SimpleAuthor;
import com.alex.common.tools.ChineseUtils;
import com.alex.webnote.dao.WebNoteDao;
import com.alex.webnote.domain.WebNotePO;
import com.alex.webnote.domain.WebNoteState;

@Controller
@RequestMapping("/webnote")
public class WebNoteController {

	private static final int EDIT_EXPORT_SIZE = 100;

	@Autowired
	private WebNoteDao webNoteDao;

	private SimpleAuthor author = SimpleAuthor.getInstance();

	@RequestMapping(method = { RequestMethod.GET })
	public String index(Model model, HttpServletRequest request) {
		List<WebNotePO> webNoteNameIds = webNoteDao.query4List(0,
				EDIT_EXPORT_SIZE, author.getUsername(request));
		model.addAttribute("webNoteNameIds", webNoteNameIds);
		return "webnote/edit";
	}

	@RequestMapping(value = "export", method = { RequestMethod.GET })
	public void export(Model model, HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		String username = author.getUsername(request);

		if (username != null) {
			// max is EDIT_EXPORT_SIZE
			List<WebNotePO> webNotes = webNoteDao.list4Export(0,
					EDIT_EXPORT_SIZE, username);

			response.setContentType("text/plain");
			response.setHeader(
					"Content-disposition",
					"attachment;filename=NoteExport"
							+ new SimpleDateFormat("yyyyMMdd")
									.format(new Date()) + ".txt");

			OutputStream out = response.getOutputStream();
			try {
				if (webNotes != null) {
					for (WebNotePO webNotePO : webNotes) {
						StringBuilder strb = new StringBuilder(
								"****************************************************************************")
								.append("\r\n");
						strb.append("【名称】").append(webNotePO.getName())
								.append("\r\n");
						strb.append("【标识】").append(webNotePO.getTags())
								.append("\r\n");
						strb.append(webNotePO.getNoteContent()).append("\r\n");
						strb.append(
								"****************************************************************************")
								.append("\r\n").append("\r\n");
						out.write(strb.toString().getBytes());
					}
				}
				out.flush();
			} finally {
				out.close();
			}
		}
	}

	private String createAlias(String name, String username, boolean isInsert,
			String oldAlias, Long oldId)
			throws BadHanyuPinyinOutputFormatCombination {
		String newAlias = ChineseUtils.toHanyuPinyinString(name, 55);
		WebNotePO po = webNoteDao.findByAlias(newAlias, username, false,
				WebNoteState.DRAFT.ordinal());
		if (isInsert) {
			// 插入
			if (po != null) {
				// 重名 - 改
				newAlias = newAlias + "_" + System.currentTimeMillis();
			}
			// 不重名 - 用
		} else {
			// 更新
			if ((oldAlias != null)
					&& (oldAlias.startsWith(newAlias))
					&& ((oldAlias.length() == newAlias.length()) || (oldAlias
							.charAt(newAlias.length()) == '_'))) {
				// 不变 - 保持旧的
				return oldAlias;
			} else {
				// 变了
				if (po != null && po.getId() != oldId) {
					// 不同记录重名 - 改
					newAlias = newAlias + "_" + System.currentTimeMillis();// +14(length)
				}
				// 不重名（或持续更新） - 用
			}
		}
		return newAlias;
	}

	@RequestMapping(value = "save", method = { RequestMethod.POST })
	public @ResponseBody
	String save(WebNotePO webNote, @RequestParam("author_") String author_,
			HttpServletRequest request, HttpServletResponse response)
			throws BadHanyuPinyinOutputFormatCombination {

		if (NumberUtils.isDigits(webNote.getName())) {
			// name不能是纯数字
			return "Note 'name' is digits error.";
		}

		String username = author.getUsername(request);
		if (username != null) {
			boolean isInsert = true;
			if (webNote.getId() != null && webNote.getId() > 0) {
				isInsert = false;
			}
			webNote.setAlias(createAlias(webNote.getName(), username, isInsert,
					webNote.getAlias(), webNote.getId()));
			webNote.setUsername(username);
			webNoteDao.save(webNote, author_, isInsert);
		} else {
			ILogger.logger_common
					.error("save username is null or no 'author_' to update.");
		}
		return webNote.getId() + "";
	}

	@RequestMapping(value = "find/{idOrAlias}", method = { RequestMethod.GET })
	public String find(@PathVariable String idOrAlias,
			HttpServletRequest request, HttpServletResponse response,
			Model model) throws IOException {
		String username = author.getUsername(request);
		if (NumberUtils.isDigits(idOrAlias)) {
			// 是数字，需要永久定位到别名
			WebNotePO webNote = webNoteDao.find(Long.valueOf(idOrAlias),
					username, false);
			if (webNote != null) {
				response.setStatus(HttpStatus.MOVED_PERMANENTLY.value());
				response.sendRedirect("/webnote/find/" + webNote.getAlias());
				return null;
			}
		}
		// 是别名
		WebNotePO webNote = webNoteDao.findByAlias(idOrAlias, username, false,
				WebNoteState.DRAFT.ordinal());
		model.addAttribute("webNote", webNote);
		return index(model, request);
	}

	@RequestMapping(value = "delete", method = { RequestMethod.GET })
	public ModelAndView delete(@RequestParam("id") Long id,
			HttpServletRequest request, Model model) {
		String username = author.getUsername(request);
		boolean ifOK = webNoteDao.delete(id, username);
		ModelAndView mv = new ModelAndView(new RedirectView("/webnote"), "msg",
				ifOK ? "Delete OK." : "Delete Failed.");
		return mv;
	}

}
